
var audio_context;
var recorder;

function sliceBlob(blob, start, end, type) {
    type = type || blob.type;
    if (blob.mozSlice) {
        return blob.mozSlice(start, end, type);
    } else if (blob.webkitSlice) {
        return blob.webkitSlice(start, end, type);
    } else {
        throw new Error("This doesn't work!");
    }
}



require([ "dojo/ready",
          "dojo/Deferred",
          "dijit/registry",
          "dojo/on",
          "dojo/request"
        ], function(ready, Deferred, registry, on, request) {
        ready(function() {

            function startUserMedia(stream) {
                var input = audio_context.createMediaStreamSource(stream);
                console.info('Media stream created.');

                input.connect(audio_context.destination);
                console.info('Input connected to audio context destination.');

                recorder = new Recorder(input);
                console.info('Recorder initialised.');
            }
        	
		    try {
		      // webkit shim
		      window.AudioContext = window.AudioContext || window.webkitAudioContext;
		      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
		      window.URL = window.URL || window.webkitURL;
		      
		      audio_context = new AudioContext;
		      console.info('Audio context set up.');
		      console.info('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
		    } catch (e) {
		      alert('No web audio support in this browser!');
		    }
		    
		    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
		      console.info('No live audio input: ' + e);
		    });
        	
        	
            //connect button callbacks
            on(registry.byId("record_btn"), 'click',function() {
            	registry.byId("record_btn").set('disabled', true);
            	registry.byId("analyze_btn").set('disabled', false);
			    recorder && recorder.record();
            })

            on(registry.byId("analyze_btn"), 'click',function() {
            	registry.byId("record_btn").set('disabled', false);
            	registry.byId("analyze_btn").set('disabled', true);
			    recorder && recorder.stop();
			    
			    recorder && recorder.exportWAV(function(blob) {
			    	console.info(blob)
                    //var data = blob.slice(0, blob.size, blob.type);
                    //console.info(data)
                    var fd = new FormData();
                    fd.append('wave', blob);
                    fd.append('sent', 'I like English');
                    fd.append('sent1', 'I like English');
                    console.info(fd);

                    var boundary = Math.random().toString().substr(2);
                    
                    console.info('before xhr');
                    request('/dsr/rec', {method:'POST',  
                                         headers : { "Content-Type" : 'multipart/form-data; boundary=' + boundary},
                                         data : fd
                                            }).then(function(score){
                                                console.info('success xhr');
                                                dojo.byId('score_label').innerHTML=score;
                                                recorder.clear();
                                            }, function(error){
                                                console.info('failed xhr');
                                                alert(error)
                                                recorder.clear();
                                            })

                    })
            })


        }); //end of ready
}); // end of require



